using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using AdvancedPoll.Models;
using System.Runtime.InteropServices;

namespace AdvancedPoll {
    [ComVisible(false)]
    public class Migrations : DataMigrationImpl {

        public int Create() {
			// Creating table PollChoiceRecord
			SchemaBuilder.CreateTable("PollChoiceRecord", table => table
				.Column("Id", DbType.Int32, column => column.PrimaryKey().Identity())
				.Column("Answer", DbType.String)
				.Column("PollPartRecord_id", DbType.Int32)
			);

			// Creating table PollResultRecord
			SchemaBuilder.CreateTable("PollResultRecord", table => table
				.Column("Id", DbType.Int32, column => column.PrimaryKey().Identity())
				.Column("Count", DbType.Int32)
				.Column("PollChoiceRecord_id", DbType.Int32)
			);

			// Creating table PollVoteRecord
			SchemaBuilder.CreateTable("PollVoteRecord", table => table
				.Column("Id", DbType.Int32, column => column.PrimaryKey().Identity())
				.Column("Username", DbType.String)
				.Column("Fingerprint", DbType.String)
				.Column("VoteDateUtc", DbType.DateTime)
				.Column("PollPartRecord_id", DbType.Int32)
				.Column("PollChoiceRecord_id", DbType.Int32)
			);

			// Creating table PollPartRecord
			SchemaBuilder.CreateTable("PollRecord", table => table
				.ContentPartRecord()
				.Column("Question", DbType.String)
				.Column<DateTime>("OpenDateUtc")
				.Column<DateTime>("CloseDateUtc")
				.Column("MaxVotes", DbType.Int32)
				.Column("Shown", DbType.Boolean)
			);

            ContentDefinitionManager.AlterPartDefinition(
                typeof(PollPart).Name, cfg => cfg.Attachable());

            return 1;
        }

        public int UpdateFrom1()
        {
            ContentDefinitionManager.AlterTypeDefinition(
                "Poll", cfg => cfg
                    .WithPart("CommonPart")
                    .WithPart("PollPart")
                    .WithPart("IdentityPart")
                    .WithPart("ContainablePart")
                    .Creatable());
            return 2;
        }

        public int UpdateFrom2()
        {
            ContentDefinitionManager.AlterTypeDefinition(
                "Poll", cfg => cfg
                    .WithPart("TitlePart"));
            return 3;
        }
    }
}